let userInfo = {
  token: '',
  dpop: '',
  userId: '',
  userName: ''
}

let detail = {
  checkCode: '',
  shopName: ''
}

/**Modal 提示 */
const openStr = `请打开 <a target="_blank" class="underline" href="https://jp.mercari.com/">https://jp.mercari.com/</a> 登录,然后重试`

/**是否错误 需要关闭插件 */
let needCloseWindow = false

$('#getData').on('click', async () => {
  // await getList2()
  handleGetData()
})

$('#closeMadal').on('click', () => {
  if (needCloseWindow) {
    window.close()
  }
  closeModal()
})

/**打开模态框 */
function openModal(msg: string) {
  $('#modal').css('display', 'block')
  $('#alertMsg').html(msg)
}
/**关闭模态框 */
function closeModal() {
  $('#modal').css('display', 'none')
  $('#alertMsg').text('')
}
/**打开loading */
function openLoading() {
  $('#loading').css('display', 'block')
}
/**关闭loading */
function closeLoading() {
  $('#loading').css('display', 'none')
  $('#progress').text(`0%`)
}
/** */
async function handleGetData() {
  const code = $('#authCode').val() as string

  // 检测是否获取用户信息
  if (!userInfo.token) {
    return openModal(openStr)
  }

  //  检测是否输入
  if (!code || code.trim() == '') {
    return openModal('请输入授权码')
  }

  openLoading()

  // 校验网站平台店铺校验码
  $fetch2({
    url: `distribution/orderMercari/checkCodeByWeb?checkCode=${code}&shopName=${userInfo.userName}`,
    method: 'GET'
  }).then(async res => {
    saveToLocal('authCode', code)
    detail.checkCode = res.data.checkCode
    detail.shopName = res.data.name
    sendMsgToContent('get-list', code)
  })
}
/** */
const sendMsgToContent = (action: string, data?: any) => {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs
      .sendMessage(tabs[0].id as number, {
        from: 'popup',
        to: 'content',
        action,
        data
      })
      .catch(e => {
        openModal(openStr)
        needCloseWindow = true
      })
  })
}
sendMsgToContent('get-user-info')
openLoading()

chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
  const { from, to, action, data } = req
  console.log(`content 收到消息 ==>`, req)
  // 判断是否是从popup发送过来的消息
  if (to == 'popup' && from == 'content') {
    switch (action) {
      case 'get-user-info' /**获取 用户信息 */:
        userInfo.dpop = data.dpop
        userInfo.token = data.token
        userInfo.userId = data.userId
        userInfo.userName = data.userName
        closeLoading()
        break
      case 'get-user-info-time-out' /**获取 用户信息超时 */:
        closeLoading()
        openModal('请登录后再试')
        needCloseWindow = true
        break
      case 'network-error' /**network-error */:
        openModal(data)
        closeLoading()
        break
      case 'close-loading' /**close-loading*/:
        closeLoading()
        break
      case 'set-progress' /**close-loading*/:
        $('#progress').text(`${data}`)
        break
      case 'open-modal' /**close-loading*/:
        openModal(data)
        closeLoading()
      case 'bad-url':
        openModal(data)
        closeLoading()
        break
      default:
        break
    }
  }
})

/**保存信息到 chrome.storage.local*/
function saveToLocal(key: string, value: any) {
  chrome.storage.local.set({ [key]: value }).then(result => {
    console.log(`保存成功 ==>`, { [key]: value })
  })
}

// 第一次显示时通过content-script的localstorage获取开启选中情况和地理位置
function setAuthCode() {
  chrome.storage.local.get(['authCode']).then(result => {
    $('#authCode').val(result.authCode || '')
  })
}
setAuthCode()

function $fetch2(param: { url: string; method?: 'GET' | 'POST'; data?: any }) {
  const { url, method = 'post', data } = param
  // 唐伟
  // const baseUrl = 'https://68m535x516.yicp.fun'
  // 线上
  const baseUrl = 'https://www.f2c.co.jp/api'

  const fetchOption = {
    method,
    headers: {
      'Content-Type': 'application/json'
    },
    body: method == 'post' ? JSON.stringify(data) : undefined
  }
  return new Promise<any>((resolve, reject) => {
    fetch(`${baseUrl}/${url}`, fetchOption)
      .then(response => response.json())
      .then(result => {
        const { code, msg } = result
        if (code == 200) {
          resolve(result)
        } else {
          openModal(msg)
          closeLoading()
          reject({})
        }
      })
      .catch(e => {
        openModal(e.message)
        closeLoading()
        reject({})
      })
  })
}
